#include "tool.h"

#include <qprocess.h>
#include <qsettings.h>
#include <QDebug>
#include <qfile.h>
#include <QDateTime>
#include "logger.h"

tool::tool()
{

}

QVariant getSetting(QString key, QString filename)
{
    QString configName = ROOT_PATH + "/conf/" + filename;
    QSettings settings(configName, QSettings::IniFormat);
    settings.setIniCodec("UTF-8");
    return settings.value(key);
}

void commitSetting(QString key, QVariant value, QString filename)
{
    QString configName = ROOT_PATH + "/conf/" + filename;
    QSettings settings(configName, QSettings::IniFormat);
    settings.setIniCodec("UTF-8");
    settings.setValue(key, value);
}


QString getSn()
{
    return execShell("sudo dmidecode -s system-serial-number");
}

QString getHostMacAddress()
{
    QProcess p;
    QString netName = getSetting("netportname").toString();
    if(netName.isEmpty()){
        netName = "eth0";
    }
    QString cmd = QString("cat /sys/class/net/%1/address").arg(netName);
    p.start(cmd);
    p.waitForFinished();
    QString mac = p.readAll().simplified();
    qDebug()<<"mac:"<<mac;
    return mac;
}

QString execShell(QString cmd)
{
    QProcess process;
    process.start("bash", QStringList() << "-c" << cmd);
    process.waitForFinished();
    QString result = process.readAll().trimmed();
    return result;
}


void writeFile(QString text, QString fileName)
{
    QFile file(fileName);
    if(file.open(QIODevice::WriteOnly | QIODevice::Text)){
        QTextStream out(&file);
        out << text;
        file.close();
    }
}

QString readFile(QString fileName)
{
    QFile file(fileName);
    if(file.open(QIODevice::ReadOnly | QIODevice::Text)){
        QTextStream in(&file);
        QString content = in.readAll();
        file.close();
        return content;
    }else{
        return nullptr;
    }
}

void writeLog(const QString &message, const QString &level) {

    static QFile file(ROOT_PATH + "/aging_log.txt");
    static bool fileOpened = false;

    if(!file.exists()){
        qDebug()<<"文件不存在,重新打开";
//        file.open(QIODevice::WriteOnly | QIODevice::Append);
        fileOpened = false;
    }

    if (!fileOpened) {
        file.open(QIODevice::WriteOnly | QIODevice::Append);
        fileOpened = true;
    }

    QTextStream textStream(&file);
    textStream << "["+QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss:ZZZ")+"]" << " "+level+"/ " << message << endl;
    file.flush();
}

QString logD(const QString &message){
    Logger::logMessage("D", message);
    return message;
}

QString logW(const QString &message){
    Logger::logMessage("W", message);
    return message;
}

QString logE(const QString &message){
    Logger::logMessage("E", message);
    return message;
}


void clearLog()
{
    Logger::clearLogFile();
}
